<template>
  <div>
    <el-form
      class="login-form"
      ref="login-form"
      :model="user"
      :rules="formRules"
      v-if="currtPage === 'login'"
    >
      <h1 class="login-logo">登录后台账号</h1>
      <div class="menu">
        <span
          @click="user.isnote = true"
          :class="user.isnote?'active':''"
        >短信登录</span>
        <span
          @click="user.isnote = false"
          :class="user.isnote?'':'active'"
        >密码登录</span>
      </div>
      <el-form-item
        prop="mobile1"
        v-if="user.isnote"
      >
        <el-input
          v-model="user.mobile1"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="code1"
        v-if="user.isnote"
        style="display:flex; justify-content: space-between; "
      >
        <el-input
          style="width:162px"
          v-model="user.code1"
          placeholder="请输入验证码"
        ></el-input>
        <div
          class="getCode "
          :class="typeof getCodeName === 'string'?'':'isGetCode'"
          @click="varifyMobile"
        >{{getCodeName}}</div>
      </el-form-item>
      <el-form-item
        prop="mobile"
        v-if="!user.isnote"
      >
        <el-input
          v-model="user.mobile"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="code"
        v-if="!user.isnote"
      >
        <el-input
          v-model="user.code"
          type="password"
          :show-password="true"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item prop="agree">
        <el-checkbox v-model="user.agree">我已阅读并同意用户协议和隐私政策</el-checkbox>
      </el-form-item>
      <el-form-item style="position: relative">
        <el-button
          type="primary"
          class="login-btn"
          :loading="loginLoading"
          @click="onLogin"
        >登录</el-button>
        <span
          class="forgetAcount"
          @click="loginPage('forgot')"
        >忘记密码</span>
      </el-form-item>
      <el-form-item class="noCountStyle">
        没有账号？ <span @click="loginPage('register')">注册新用户</span>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login, getVerificationCode } from '@/api/user' // loginExtra
import Cookies from 'js-cookie'
import jwt from 'jsonwebtoken'
export default {
  data () {
    return {
      getCodeName: '获取验证码',
      timer: null,
      currtPage: 'login',
      user: {
        mobile1: '18706064133', // 用于获取验证码
        code1: '', // 验证码
        mobile: '18706064133',
        code: '123456',
        agree: false,
        isnote: true
      },
      loginLoading: false,
      formRules: {
        // 验证规则
        mobile1: [
          { required: true, message: '手机号不能为空', trigger: 'change' },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'change'
          }
        ],
        code1: [
          { required: true, message: '验证码不能为空', trigger: 'change' },
          {
            pattern: /^\d{6}$/,
            message: '验证码长度为6位数字',
            trigger: 'change'
          }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'change' },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          {
            pattern: /^\d{6}$/,
            message: '密码长度为6位数字',
            trigger: 'change'
          }
        ],
        agree: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback()
              }
              callback(new Error('请勾选用户协议'))
            },
            // message: '手机号不能为空',
            trigger: 'change'
          }
        ]
      }
    }
  },

  methods: {
    varifyMobile () {
      // mobile1换成你想监听的prop字段
      this.$refs['login-form'].validateField('mobile1', valid => {
        if (valid) {
          return
        }
        // 调用登录接口
        this.getCode()
      })
    },
    getCode () {
      if (this.getCodeName === '获取验证码') {
        this.getCodeName = 60
        getVerificationCode({
          phone: this.user.mobile1
        }).then(
          res => {
            // console.log(res)
          },
          res => {
            this.getCodeName = '获取验证码'
            clearInterval(this.timer)
            // console.log(res)
          }
        )
        this.timer = setInterval(() => {
          if (this.getCodeName <= 0) {
            this.getCodeName = '获取验证码'
            clearInterval(this.timer)
          } else {
            this.getCodeName--
          }
        }, 1000)
      }
    },
    setSecret () {
      let obj = null
      if (this.user.isnote) {
        // 使用短信登录
        const { mobile1, code1, isnote } = this.user
        obj = { mobile1, code1, isnote }
      } else {
        // 使用账号密码登录
        const { mobile, code, isnote } = this.user
        obj = { mobile, code, isnote }
        obj.code = jwt.sign(obj.code, 'luo')
        // console.log(obj.code)
      }
      // const obj = { ...this.user }
      // obj.code = jwt.sign(obj.code, 'luo')
      // console.log(obj)
      const token = jwt.sign(obj, 'lmb') // 加密算法
      // console.log(token)
      return Cookies.get('SESSION') + token
      // return token
    },
    onLogin () {
      if (!Cookies.get('SESSION')) {
        this.getJson()
      }
      // 表单校验规则验证
      this.$refs['login-form'].validate((valid, err) => {
        if (!valid) {
          return
        }
        // 调用登录接口
        this.login()
      })
    },
    login () {
      this.loginLoading = true
      // 发送请求
      const token = this.setSecret()
      login(token).then(
        res => {
          setTimeout(() => {
            this.loginLoading = false
            this.$message({
              message: '登录成功',
              type: 'success'
            })
            this.$router.push({
              name: 'home'
            })
          }, 300)
        },
        err => {
          console.log('登陆失败', err)
          this.loginLoading = false
        }
      )

      // 本地调试写法
      // loginExtra(token).then(
      //   res => {
      //     // console.log(res)
      //     // 本地调试写法
      //     Cookies.set('hello', res.data.hello, { expires: 1 })

      //     setTimeout(() => {
      //       this.loginLoading = false
      //       this.$message({
      //         message: '登录成功',
      //         type: 'success'
      //       })
      //       this.$router.push({
      //         name: 'home'
      //       })
      //     }, 300)
      //   },
      //   err => {
      //     // console.log('登陆失败', err)
      //     this.$message({
      //       message: '登录失败',
      //       type: 'success'
      //     })
      //     this.loginLoading = false
      //   }
      // )
    },
    loginPage (currtPage) {
      this.$emit('changeState', currtPage)
    }
  }
}
</script>

<style lang='less' scoped>
.login-logo {
  width: 300px;
  font-size: 18px;
  text-align: center;
  color: #333;
  margin-bottom: 12px;
}
.menu {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
  span {
    font-size: 18px;
    cursor: pointer;
  }
}
.getCode {
  width: 120px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  display: inline-block;
  background: #409eff;
  color: #fff;
  border-radius: 3px;
  margin-left: 18px;
  cursor: pointer;
  border-radius: 10px;
}
.isGetCode {
  opacity: 0.65;
}
.active {
  font-weight: bolder;
}
.login-form {
  background-color: #fff;
  padding: 30px 50px 0px;
  min-width: 300px;
  .login-btn {
    width: 50%;
    position: absolute;
    border-radius: 40px;
    left: 50%;
    transform: translateX(-50%);
  }
  .forgetAcount {
    position: absolute;
    left: 80%;
    top: 35px;
    color: #409eff;
    cursor: pointer;
  }
}

.noCountStyle {
  margin-top: 80px;
  border-top: 1px solid #e4e7ec;
  text-align: center;
  padding: 10px 0 20px;
  color: #333;
  span {
    color: #409eff;
    cursor: pointer;
  }
}
</style>
